package cn.shiro.shiroservice.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.InputBuffer;

import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;

/**
 * &#064;Time 2024 二月 星期六 14:52
 *
 * @author ShangGuan
 */
@Slf4j
public class FileUtils {


    /**
     * 存在
     *
     * @param path 路径
     * @return boolean
     */

    public static boolean exists(String path) {
        File file = new File(path);
        return file.exists();
    }


    /**
     * 创建路径
     *
     * @param path 路径
     */

    public static void createPath(String path) {
        File file = new File(path);
        boolean exists = exists(path);
        if (!exists) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建文件失败");
            }
        }
        printlnFilePermissions(path);
    }

    /**
     * 打印文件权限
     *
     * @param path 路径
     */

    public static void printlnFilePermissions(String path) {
        try {
            PosixFileAttributes attrs = Files.readAttributes(FileSystems.getDefault().getPath(path), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            log.info("Owner:{}", attrs.owner().getName());
            log.info("Group:{}", attrs.group().getName());
            log.info("Permissions:{}", PosixFilePermissions.toString(attrs.permissions()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 写出数据
     */
    public static void write(String content, File file) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            writer.write(content);
            log.info("保存成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取str
     *
     * @param file 文件
     * @return {@link String}
     */

    public static String readStr(File file){
        StringBuilder content  = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))){
            String read ;
            while ((read=reader.readLine())!=null){
                content.append(read);
            }
            return content.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
